package com.jx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiResult;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jx.common.utils.StringUtils;
import com.jx.entity.CreditQueryLog;
import com.jx.entity.UserCredit;
import com.jx.mapper.UserCreditMapper;
import com.jx.service.CreditQueryLogService;
import com.jx.service.UserCreditService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 *
 * @author Administrator
 */
@Service
public class UserCreditServiceImpl extends ServiceImpl<UserCreditMapper, UserCredit>
    implements UserCreditService{

    @Autowired
    private CreditQueryLogService creditQueryLogService;

    /** 计算操作消耗时间 */
    private static final ThreadLocal<Long> TIME_THREADLOCAL = new NamedThreadLocal<>("Cost Time");

    @Override
    public ApiResult<Object> queryCredit(CreditQueryLog query) {
        TIME_THREADLOCAL.set(System.currentTimeMillis());
        if(StringUtils.isEmpty(query.getUserName())||StringUtils.isEmpty(query.getPhone())||StringUtils.isEmpty(query.getIdCard())){
            return getErrorResult(query,"参数不能为空");
        }

        if(query.getUserName().length()>20){
            query.setUserName(query.getUserName().substring(0,20));
            return getErrorResult(query,"无效的姓名");
        }

        if(!StringUtils.isValidPhoneNumber(query.getPhone())){
            if (query.getPhone().length() > 11) {
                query.setPhone(query.getPhone().substring(0,11));
            }
            return getErrorResult(query,"无效的手机号码");
        }

        if(!StringUtils.isValidIdNumber(query.getIdCard())){
            if (query.getIdCard().length() > 18) {
                query.setIdCard(query.getIdCard().substring(0,18));
            }
            return getErrorResult(query,"无效的身份证号码");
        }

        QueryWrapper<UserCredit> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(UserCredit::getUserName,query.getUserName())
                .eq(UserCredit::getIdCard,query.getIdCard());
        List<UserCredit> userList = this.list(wrapper);
        String creditRating = "A";
        String result = "无匹配，返回：A";
        if (userList!=null && userList.size()>0){
            if(!StringUtils.isEmpty(userList.get(0).getCreditRating())){
                creditRating = userList.get(0).getCreditRating();
                result = String.format("匹配到用户ID：%s，已设置信用等级，返回：%s",userList.get(0).getUserId(),creditRating);
            }else{
                result = String.format("匹配到用户ID：%s，未设置信用等级，返回：A",userList.get(0).getUserId());
            }
        }
        query.setJsonResult(result);
        query.setOperTime(new Date());
        query.setCostTime(System.currentTimeMillis() - TIME_THREADLOCAL.get());
        creditQueryLogService.saveOrUpdate(query);
        return ApiResult.ok(creditRating);
    }

    private ApiResult<Object> getErrorResult(CreditQueryLog query, String errorMsg) {
        query.setJsonResult("查询失败："+errorMsg);
        query.setOperTime(new Date());
        query.setCostTime(System.currentTimeMillis() - TIME_THREADLOCAL.get());
        creditQueryLogService.saveOrUpdate(query);
        return ApiResult.failed(errorMsg);
    }

}
